local extension = Package("ling6")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"

local lishimin = General(extension, "lingling__lishimin", "tang", 4)
local lingjian = fk.CreateActiveSkill{
  name = "lingling__lingjian",
  frequency = Skill.Limited,
  card_num = 0,
  target_num = 0,
  prompt = "#lingling__lingjian",
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and player.role ~= "renegade" and
      table.find(Fk:currentRoom().players, function (p)
        return p.dead and (p.role == "rebel" or p.role == "loyalist")
      end)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:doIndicate(player.id, table.map(room.alive_players, Util.IdMapper))
    for _, p in ipairs(room.alive_players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end
    local renegades = table.filter(room:getOtherPlayers(player, false, true), function (p)
      return p.role == "renegade"
    end)
    if #renegades == 0 then return end
    for _, p in ipairs(renegades) do
      if player.dead then return end
      if not p.dead then
        local choices = {}
        for _, q in ipairs(room.players) do
          if q.dead then
            if q.role == "loyalist" then
              table.insertIfNeed(choices, "loyalist")
            elseif q.role == "rebel" then
              table.insertIfNeed(choices, "rebel")
            end
          end
        end
        if #choices > 0 then
          local choice = room:askForChoice(player, choices, self.name, "#lingling__lingjian-choice::"..p.id)
          room:doIndicate(player.id, {p.id})
          p.role = choice
          room:sendLog{
            type = "#LingjianChoiceBroadcast",
            from = player.id,
            to = {p.id},
            arg = choice,
          }
          room:setPlayerProperty(p, "role_shown", true)
          room:broadcastProperty(p, "role")
          if choice == "loyalist" then
            for _, q in ipairs(room:getAlivePlayers()) do
              if q.role == "rebel" and not q.dead then
                if q:isWounded() then
                  room:recover{
                    who = p,
                    num = 1,
                    recoverBy = player,
                    skillName = self.name,
                  }
                end
                if not q.dead then
                  q:drawCards(1, self.name)
                end
              end
            end
          elseif choice == "rebel" then
            local lord = room:getLord()
            if lord == nil then
              lord = table.find(room.alive_players, function (q)
                return q.seat == 1
              end)
            end
            if lord == nil then return end
            local n = #table.filter(room.alive_players, function (q)
              return q.role == "rebel"
            end)
            if n > 0 then
              if lord:isWounded() then
                room:recover{
                  who = lord,
                  num = math.min(n, lord.maxHp - lord.hp),
                  recoverBy = player,
                  skillName = self.name,
                }
              end
              if not lord.dead then
                lord:drawCards(n, self.name)
              end
            end
          end
        else
          return
        end
      end
    end
  end,
}
local mingshi = fk.CreateTriggerSkill{
  name = "lingling__mingshi",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.DrawNCards, fk.Damage},
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.DrawNCards then
        return table.find(player.room.alive_players, function (p)
          return p.role == "loyalist"
        end)
      elseif event == fk.Damage then
        return data.card and data.card.trueName == "slash" and
          table.find(player.room.alive_players, function (p)
            return p.role == "renegade"
          end)
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.DrawNCards then
      data.n = data.n + 1
    elseif event == fk.Damage then
      player.room:changeShield(player, 1)
    end
  end,
}
local mingshi_targetmod = fk.CreateTargetModSkill{
  name = "#lingling__mingshi_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:hasSkill(mingshi) and player.phase == Player.Play and
      table.find(Fk:currentRoom().alive_players, function (p)
        return p.role == "rebel"
      end) then
        return 1
    end
  end,
}
local mingshi_maxcard = fk.CreateMaxCardsSkill{
  name = "#lingling__mingshi_maxcard",
  correct_func = function(self, player)
    if player:hasSkill(mingshi) and table.every(Fk:currentRoom().players, function (p)
      return not p.dead
    end) and player.phase == Player.Discard then
      return 1
    end
  end,
}
mingshi:addRelatedSkill(mingshi_targetmod)
mingshi:addRelatedSkill(mingshi_maxcard)
lishimin:addSkill(lingjian)
lishimin:addSkill(mingshi)
Fk:loadTranslationTable{
  ["lingling__lishimin"] = "李世民",
  ["#lingling__lishimin"] = "天可汗",
  ["designer:lingling__lishimin"] = "伶",
  ["illustrator:lingling__lishimin"] = "珊瑚虫",
  ["lingling__lingjian"] = "灵鉴",
  [":lingling__lingjian"] = "限定技，出牌阶段，若你不为内奸，且有忠臣/反贼已死亡，你可以令所有角色翻开身份牌，将内奸换为忠臣/反贼，"..
  "若换为忠臣，反贼各回复1点体力并各摸一张牌；若换为反贼，主公回复X点体力并摸X张牌（X为存活反贼数）。",
  ["lingling__mingshi"] = "命世",
  [":lingling__mingshi"] = "锁定技，摸牌阶段，若仍有忠臣存活，你摸牌数+1。出牌阶段，若仍有反贼存活，你使用【杀】的次数上限+1。"..
  "当你使用【杀】造成伤害后，若仍有内奸存活，你护甲+1。弃牌阶段，若没有已死亡角色，你手牌上限+1。"..
  "<br><br> <font color='#a40000'>尔来一百九十载，天下至今歌舞之。</font>",
  ["#lingling__lingjian"] = "灵鉴：你可以令所有角色展示身份并修改内奸身份！",
  ["#lingling__lingjian-choice"] = "灵鉴：选择 %dest 变为的身份",
  ["#LingjianChoiceBroadcast"] = "%from 将 %to 的身份变成了 %arg",

  ["$lingling__lingjian1"] = "我唐既得天命以承四海，平不平者，同愿同人。",
  ["$lingling__lingjian2"] = "大唐有你，才真的了不起！",
}

local wuzhao = General(extension, "lingling__wuzhao", "tang", 3, 3, General.Female)
local dangguo = fk.CreateTriggerSkill{
  name = "lingling__dangguo",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.card.type == Card.TypeEquip
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
    if table.contains({5, 9}, #player:getCardIds("h")) and #player.room.alive_players > 0 then
      local luckyOne = table.random(player.room.alive_players, 1)[1]
      player.room:doIndicate(player.id, {luckyOne.id})
      luckyOne:drawCards(2, self.name)
      if not luckyOne.dead then
        luckyOne:turnOver()
      end
    end
  end,
}
local qiangzhong = fk.CreateTriggerSkill{
  name = "lingling__qiangzhong",
  anim_type = "offensive",
  events = {fk.TurnedOver, fk.ChainStateChanged},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event == fk.TurnedOver then
      return not target.faceup and not target.dead
    else
      return target.chained and not target.dead
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local cid = room:askForDiscard(player, 1, 1, true, self.name, true, ".", "#lingling__qiangzhong-invoke:" .. target.id)
    if #cid == 1 then
      self.cost_data = {tos = {target.id}, cards = cid}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, self.name, player, player)
    if player.dead or target.dead then return end
    local choice = room:askForChoice(player, {"lingling__qiangzhong_damage", "lingling__qiangzhong_draw"}, self.name,
      "#lingling__qiangzhong-choice::"..target.id)
    if choice == "lingling__qiangzhong_damage" then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    else
      target:drawCards(2, self.name)
    end
  end,
}
local shenlong = fk.CreateTriggerSkill{
  name = "lingling__shenlong",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target == player
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if #player:getCardIds("he") > 1 then
      local cids = room:askForDiscard(player, 2, 2, true, self.name, true, ".", "#lingling__shenlong-discard")
      if #cids < 2 then
        player:turnOver()
      end
    else
      player:turnOver()
    end
  end,
}
wuzhao:addSkill(dangguo)
wuzhao:addSkill(qiangzhong)
wuzhao:addSkill(shenlong)
Fk:loadTranslationTable{
  ["lingling__wuzhao"] = "武曌",
  ["#lingling__wuzhao"] = "天后",
  ["designer:lingling__wuzhao"] = "伶",
  ["illustrator:lingling__wuzhao"] = "珊瑚虫",
  ["lingling__dangguo"] = "荡国",
  [":lingling__dangguo"] = "锁定技，当一名角色使用装备牌后，你摸一张牌，然后若你手牌数为9或5，随机一名角色摸两张牌并翻面。",
  ["lingling__qiangzhong"] = "戕忠",
  [":lingling__qiangzhong"] = "当一名角色翻至背面或横置后，你可以弃置一张牌，然后选择对其造成1点伤害或令其摸两张牌。",
  ["#lingling__qiangzhong-invoke"] = "戕忠：你可以弃置一张牌，对 %src 造成1点伤害或令其摸两张牌",
  ["#lingling__qiangzhong-choice"] = "戕忠：选择对 %dest 执行的一项",
  ["lingling__qiangzhong_damage"] = "对其造成1点伤害",
  ["lingling__qiangzhong_draw"] = "令其摸两张牌",
  ["lingling__shenlong"] = "神龙",
  [":lingling__shenlong"] = "锁定技，当你受到伤害后，你弃置两张牌，否则翻面。"..
  "<br><br> <font color='#a40000'>圣母临朝，日月当空。</font>",
  ["#lingling__shenlong-discard"] = "神龙：你须选择两张牌弃置，或点取消并翻面",
}

local libai = General(extension, "lingling__libai", "tang", 3)
local jiushi = fk.CreateViewAsSkill{
  name = "lingling__jiushi",
  anim_type = "special",
  pattern = "analeptic",
  card_filter = function(self, to_select, selected)
    return #selected < 2
  end,
  view_as = function(self, cards)
    if #cards ~= 2 then return end
    local card = Fk:cloneCard("analeptic")
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    player.room:setPlayerMark(player, "lingling__jiushi-turn", 1)
  end,
  enabled_at_play = function(self, player)
    return player:getMark("lingling__jiushi-turn") == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:getMark("lingling__jiushi-turn") == 0
  end,
}
local jiushi_trigger = fk.CreateTriggerSkill{
  name = "#lingling__jiushi_trigger",
  mute = true,
  main_skill = jiushi,
  events = {fk.TurnEnd, fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(jiushi) then
      return
    end
    if event == fk.TurnEnd then
      return player.drank > 0
    else
      return data.card.name == "analeptic" and target == player
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    --player:broadcastSkillInvoke(jiushi)
    if event == fk.TurnEnd then
      room:notifySkillInvoked(player, jiushi.name, "drawcard")
      player:drawCards(3, jiushi.name)
    else
      room:notifySkillInvoked(player, jiushi.name, "special")
      local cards = table.filter(room.draw_pile, function (id)
        return Fk:getCardById(id).type == Card.TypeTrick
      end)
      if #cards > 0 then
        room:obtainCard(player, table.random(cards, 1), false, fk.ReasonJustMove)
      end
    end
  end
}
local denglou = fk.CreateDistanceSkill{
  name = "lingling__denglou",
  frequency = Skill.Compulsory,
  correct_func = function(self, from, to)
    if to:hasSkill(self) and from:getMark("lingling__denglou_mark-turn") == 0 and from ~= to then
      return 2
    end
  end,
  fixed_func = function (self, from, to)
    if to:hasSkill(self) and from:getMark("lingling__denglou_mark-turn") > 0 then
      return 1
    end
  end,
}
local denglou_record = fk.CreateTriggerSkill{
  name = "#lingling__denglou_record",

  refresh_events = {fk.CardUsing},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self, true) and not target.dead and data.card.type == Card.TypeTrick and
      target:getMark("lingling__denglou_mark-turn") == 0
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(target, "lingling__denglou_mark-turn", 1)
  end,
}
jiushi:addRelatedSkill(jiushi_trigger)
denglou:addRelatedSkill(denglou_record)
libai:addSkill(jiushi)
libai:addSkill(denglou)
Fk:loadTranslationTable{
  ["lingling__libai"] = "李白",
  ["#lingling__libai"] = "谪仙人",
  ["designer:lingling__libai"] = "伶",
  ["illustrator:lingling__libai"] = "珊瑚虫",
  ["lingling__jiushi"] = "酒诗",
  [":lingling__jiushi"] = "任意回合结束时若你醉酒，你摸三张牌。每回合限一次，你可以将两张牌当【酒】使用。当你使用【酒】后随机获得一张锦囊牌。",
  ["lingling__denglou"] = "登楼",
  [":lingling__denglou"] = "锁定技，本回合未使用锦囊牌的角色计算与你的距离+2，使用过锦囊牌的角色计算与你的距离为1。"..
  "<br><br> <font color='#a40000'>天子呼来不上船，自称臣是酒中仙。</font>",
}

local anlushan = General(extension, "lingling__anlushan", "tang", 8)
local tunzi = fk.CreateTriggerSkill{
  name = "lingling__tunzi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local num = player.hp - #player:getCardIds("h")
    if num > 0 then
      local suc
      local equips = {}
      local equipNum = math.floor(num / 2)
      local cards = table.filter(room.draw_pile, function (id)
        return Fk:getCardById(id).type == Card.TypeEquip
      end)
      if #cards == 0 then
        suc = true
        num = equipNum
      elseif equipNum > 0 then
        equips = table.random(cards, math.min(#cards, equipNum))
        num = num - #equips
      end
      local draws = {}
      for i = 1, 999 do
        local id = room.draw_pile[i]
        if not id then break end
        if not table.contains(equips, id) then
          table.insert(draws, id)
        end
        if #draws >= num then break end
      end
      room:obtainCard(player, table.connect(equips, draws), false, fk.ReasonDraw)
      if not player.dead and suc then
        room:loseHp(player, 1, self.name)
      end
    end
    return true
  end,
}
local meishang = fk.CreateTriggerSkill{
  name = "lingling__meishang",
  anim_type = "defensive",
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__meishang-invoke")
  end,
  on_use = function(self, event, target, player, data)
    player.room:changeMaxHp(player, -2)
    return true
  end,
}
local getLordsHandCardsNum = function ()
  local lord = table.filter(Fk:currentRoom().alive_players, function (p)
    return p.role == "lord"
  end)
  if #lord ~= 1 then
    lord = table.filter(Fk:currentRoom().alive_players, function (p)
      return p.seat == 1
    end)
  end
  if #lord == 0 then
    return 1
  end
  lord = lord[1]
  return math.max(#lord:getCardIds("h"), 1)
end
local daolong = fk.CreateViewAsSkill{
  name = "lingling__daolong",
  anim_type = "special",
  pattern = "duel",
  prompt = function ()
    return "#lingling__daolong-prompt:::" .. tostring(getLordsHandCardsNum())
  end,
  times = function(self)
    return 2 - Self:usedSkillTimes(self.name, Player.HistoryTurn)
  end,
  card_filter = function(self, to_select, selected)
    return #selected < getLordsHandCardsNum() and Fk:getCardById(to_select).type == Card.TypeEquip
  end,
  view_as = function(self, cards)
    if #cards ~= getLordsHandCardsNum() then return end
    local card = Fk:cloneCard("duel")
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) < 2
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:usedSkillTimes(self.name, Player.HistoryTurn) < 2
  end,
}
anlushan:addSkill(tunzi)
anlushan:addSkill(meishang)
anlushan:addSkill(daolong)
Fk:loadTranslationTable{
  ["lingling__anlushan"] = "安禄山",
  ["#lingling__anlushan"] = "犯阙凶羯",
  ["designer:lingling__anlushan"] = "伶",
  ["illustrator:lingling__anlushan"] = "珊瑚虫",
  ["lingling__tunzi"] = "囤辎",
  [":lingling__tunzi"] = "锁定技，摸牌阶段，你改为将手牌摸至X张（X为你体力值），以此法摸的牌一半会为随机装备牌（向下取整，下同），"..
  "若牌堆已没有装备牌，则少摸一半牌，你失去1点体力。",
  ["lingling__meishang"] = "媚上",
  [":lingling__meishang"] = "当你受到伤害时，你可以减2点体力上限防止之。",
  ["lingling__daolong"] = "捣龙",
  [":lingling__daolong"] = "每回合限两次，你可以将X张装备牌当【决斗】使用（X为主公的手牌数且至少为1）。"..
  "<br><br> <font color='#a40000'>乱幽州者，必此胡也。</font>",
  ["#lingling__meishang-invoke"] = "媚上：是否减2点体力上限，防止你受到的伤害？",
  ["#lingling__daolong-prompt"] = "捣龙：你可以将 %arg 张装备牌当【决斗】使用",
}

local lilongji = General(extension, "lingling__lilongji", "tang", 4)
local shuairong = fk.CreateActiveSkill{
  name = "lingling__shuairong",
  anim_type = "control",
  card_num = 0,
  target_num = 0,
  prompt = "#lingling__shuairong",
  interaction = function()
    return UI.ComboBox { choices = {"2", "4"} }
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:doIndicate(player.id, table.map(room.alive_players, Util.IdMapper))
    local num = tonumber(self.interaction.data)
    for _, p in ipairs(room:getAlivePlayers()) do
      if not p.dead then
        local cnum = num - p:getHandcardNum()
        if cnum > 0 then
          local cids = p:drawCards(cnum, self.name)
          if #cids > 2 and not p.dead then
            p:turnOver()
          end
        elseif cnum < 0 then
          cnum = - cnum
          local cids = room:askForDiscard(p, cnum, cnum, false, self.name, false)
          if #cids > 2 and not player.dead then
            player:turnOver()
          end
        end
      end
    end
  end,
}
local cuochong = fk.CreateTriggerSkill{
  name = "lingling__cuochong",
  anim_type = "control",
  events = {fk.TurnedOver},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and not target.dead and not target.faceup
  end,
  on_cost = function (self, event, target, player, data)
    local all_choices = {"lingling__cuochong_draw:"..player.id, "lingling__cuochong_discard:"..player.id, "Cancel"}
    local choices = table.simpleClone(all_choices)
    if player:isNude() then
      table.remove(choices, 2)
    end
    local choice = player.room:askForChoice(target, choices, self.name, "#lingling__cuochong-choice:"..player.id, false, all_choices)
    if choice ~= "Cancel" then
      self.cost_data = {choice = choice}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:doIndicate(target.id, {player.id})
    if self.cost_data.choice:startsWith("lingling__cuochong_draw") then
      player:drawCards(1, self.name)
    else
      room:askForDiscard(player, 1, 1, true, self.name, false)
    end
  end,
}
local bozheng = fk.CreateTriggerSkill{
  name = "lingling__bozheng",
  priority = 2,
  anim_type = "support",
  frequency = Skill.Limited,
  events = {fk.TurnedOver},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and not target.dead and not target.faceup and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_cost = function (self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name, nil, "#lingling__bozheng-invoke::"..target.id) then
      self.cost_data = {tos = {target.id}}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    target:drawCards(2, self.name)
    if not target.dead then
      target:turnOver()
    end
  end,
}
lilongji:addSkill(shuairong)
lilongji:addSkill(cuochong)
lilongji:addSkill(bozheng)
Fk:loadTranslationTable{
  ["lingling__lilongji"] = "李隆基",
  ["#lingling__lilongji"] = "再开唐统",
  ["designer:lingling__lilongji"] = "伶",
  ["illustrator:lingling__lilongji"] = "珊瑚虫",
  ["lingling__shuairong"] = "衰荣",
  [":lingling__shuairong"] = "出牌阶段限一次，你可以令所有角色依次将手牌调整至两张或四张。若有角色因此：摸了至少三张牌，其翻面；"..
  "弃置了至少三张牌，你翻面。",
  ["lingling__cuochong"] = "错宠",
  [":lingling__cuochong"] = "当一名角色翻至背面后，其可以令你摸一张牌或弃置一张牌。",
  ["lingling__bozheng"] = "拨正",
  [":lingling__bozheng"] = "限定技，当一名角色翻至背面时，你可以令其翻至正面并摸两张牌。"..
  "<br><br> <font color='#a40000'>巍冠攒叠碧雪花，坐阅山中几岁华。<br>莫把金丹轻点化，正愁生死困安家。</font>",
  ["#lingling__shuairong"] = "衰荣：令所有角色将手牌调整至2或4",
  ["#lingling__shuairong-discard"] = "衰荣：你须弃置 %arg 张牌",
  ["#lingling__cuochong-choice"] = "错宠：你可以令 %src 执行一项",
  ["lingling__cuochong_draw"] = "%src 摸一张牌",
  ["lingling__cuochong_discard"] = "%src 弃置一张牌",
  ["#lingling__bozheng-invoke"] = "拨正：是否令 %dest 翻至正面并摸两张牌？",

  ["$lingling__bozheng1"] = "拨乱世，反诸正，君王者当如是。",
  ["$lingling__bozheng2"] = "至东都，赦天下，神龙易位，再开唐统。",
}

local fangxuanling = General(extension, "lingling__fangxuanling", "tang", 3)
local wenge = fk.CreateTriggerSkill{
  name = "lingling__wenge",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw
  end,
  on_cost = function (self, event, target, player, data)
    local targets = player.room:getOtherPlayers(player)
    targets = table.map(targets, Util.IdMapper)
    local tos = player.room:askForChoosePlayers(player, targets, 1, 999, "#lingling__wenge-invoke", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = self.cost_data
    room:sortPlayersByAction(tos)
    player:drawCards(1, self.name)
    room:setPlayerMark(player, "@@lingling__wenge_mark-turn", 1)
    for _, id in ipairs(tos) do
      local to = room:getPlayerById(id)
      if not to.dead then
        to:drawCards(1, self.name)
        if not to.dead then
          room:setPlayerMark(to, "@@lingling__wenge_mark-turn", 1)
        end
      end
    end
    room.logic:getCurrentEvent():findParent(GameEvent.Turn):addCleaner(function()
      local tos = table.map(room.alive_players, Util.IdMapper)
      room:sortPlayersByAction(tos)
      for _, id in ipairs(tos) do
        local to = room:getPlayerById(id)
        if not to.dead and #to:getCardIds("h") == 3 then
          to:drawCards(1, self.name)
        end
      end
      for _, id in ipairs(tos) do
        local to = room:getPlayerById(id)
        if not to.dead and to.maxHp == 3 then
          to:drawCards(1, self.name)
        end
      end
    end)
    return true
  end,
}
local zhuanshi = fk.CreateTriggerSkill{
  name = "lingling__zhuanshi",
  anim_type = "drawcard",
  frequency = Skill.Limited,
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and
      table.find(player.room:getBanner("@$CenterArea"), function (id)
        return Fk:getCardById(id).type ~= Card.TypeBasic
      end)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local cards = table.filter(room:getBanner("@$CenterArea"), function (id)
      return Fk:getCardById(id).type ~= Card.TypeBasic
    end)
    room:obtainCard(player, cards, true, fk.ReasonJustMove)
    if not player.dead and #cards > 3 then
      player:turnOver()
    end
  end,
}
zhuanshi.CenterArea = true
fangxuanling:addSkill(wenge)
fangxuanling:addSkill(zhuanshi)
Fk:loadTranslationTable{
  ["lingling__fangxuanling"] = "房玄龄",
  ["#lingling__fangxuanling"] = "房谋杜断",
  ["designer:lingling__fangxuanling"] = "伶",
  ["illustrator:lingling__fangxuanling"] = "珊瑚虫",
  ["lingling__wenge"] = "文阁",
  [":lingling__wenge"] = "摸牌阶段，你可以改为与任意名其他角色各摸一张牌，回合结束时，你们中手牌数为3的角色摸一张牌，体力上限为3的角色再摸一张牌。",
  ["#lingling__wenge-invoke"] = "文阁：你可以选择任意名其他角色，你与这些角色依次摸一张牌",
  ["@@lingling__wenge_mark-turn"] = "文阁",
  ["lingling__zhuanshi"] = "撰史",
  [":lingling__zhuanshi"] = "限定技，其他角色回合结束时，你可以获得中央区所有锦囊牌和装备牌，若你获得了至少四张牌，你翻面。"..
  "<br><br> <font color='#a40000'>辅相文皇功居第一，遗表之谏精忠贯日。</font>",

  ["$lingling__zhuanshi1"] = "古今明主盖以鉴古而隆运，而灵炀之流以戏史而废位。",
  ["$lingling__zhuanshi2"] = "千秋鸿毛，皆在笔下。",
}

local lijing = General(extension, "lingling__lijing", "tang", 4)
local shenwuCheck = function (card)
  return (card.trueName == "slash" and card.name ~= "slash") or
    (card.is_damage_card and card.type == Card.TypeTrick) or
    card.sub_type == Card.SubtypeWeapon
end
local shenwu = fk.CreateTriggerSkill{
  name = "lingling__shenwu",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished, fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) or player ~= target then return end
    if event == fk.CardUseFinished then
      return shenwuCheck(data.card)
    elseif event == fk.TurnEnd then
      return #player.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        local use = e.data[1]
        return use.from == player.id and shenwuCheck(use.card)
      end, Player.HistoryTurn) == 0
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local cids = {}
    if event == fk.CardUseFinished then
      if data.card.trueName == "slash" and data.name ~= "slash" then
        cids = room:getCardsFromPileByRule(".|.|.|.|.|trick")
      elseif data.card.is_damage_card and data.card.type == Card.TypeTrick then
        cids = room:getCardsFromPileByRule(".|.|.|.|.|equip")
      else
        cids = room:getCardsFromPileByRule("slash")
      end
    elseif event == fk.TurnEnd then
      for _, id in ipairs(room.draw_pile) do
        if shenwuCheck(Fk:getCardById(id)) then
          table.insert(cids, id)
        end
      end
      if #cids > 0 then
        cids = table.random(cids, 1)
      end
    end
    if #cids > 0 then
      local moveMark = Fk:getCardById(cids[1]).trueName == "slash" and "@@lingling__shenwu-inhand-turn" or nil
      room:moveCardTo(cids, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id, moveMark)
    end
  end,
}
local shenwu_targetmod = fk.CreateTargetModSkill{
  name = "#lingling__shenwu_targetmod",
  bypass_times = function (self, player, skill, scope, card, to)
    return card:getMark("@@lingling__shenwu-inhand-turn") > 0
  end
}
local suzhong = fk.CreateTriggerSkill{
  name = "lingling__suzhong",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.Deathed},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and (target.role == "rebel" or target.role == "loyalist")
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if target.role == "rebel" then
      room:notifySkillInvoked(player, self.name, "support")
      if player:isWounded() then
        local choice = room:askForChoice(player, {"draw2", "recover"}, self.name)
        if choice == "draw2" then
          player:drawCards(2, self.name)
        else
          room:recover{
            who = player,
            num = 1,
            skillName = self.name,
          }
        end
      else
        player:drawCards(2, self.name)
      end
    else
      room:notifySkillInvoked(player, self.name, "negative")
      local cids = room:askForDiscard(player, 2, 2, true, self.name, true, ".", "#lingling__suzhong-discard")
      if #cids ~= 2 then
        room:loseHp(player, 1, self.name)
      end
    end
  end,
}
shenwu:addRelatedSkill(shenwu_targetmod)
lijing:addSkill(shenwu)
lijing:addSkill(suzhong)
Fk:loadTranslationTable{
  ["lingling__lijing"] = "李靖",
  ["#lingling__lijing"] = "大唐军神",
  ["designer:lingling__lijing"] = "伶",
  ["illustrator:lingling__lijing"] = "珊瑚虫",
  ["lingling__shenwu"] = "神武",
  [":lingling__shenwu"] = "锁定技，当你使用非普通【杀】后，你随机获得一张锦囊牌。当你使用伤害类锦囊牌后，你随机获得一张装备牌。当你使用武器牌后，"..
  "你随机获得一张【杀】（本回合使用无次数限制）。回合结束时，若你以上三种牌均未使用，你随机获得其中一张。",
  ["lingling__suzhong"] = "夙忠",
  [":lingling__suzhong"] = "锁定技，当一名反贼死亡后，你回复1点体力或摸两张牌。当一名忠臣死亡后，你失去1点体力或弃置两张牌。"..
  "<br><br> <font color='#a40000'>兼资文武，出将入相。</font>",
  ["#lingling__suzhong-discard"] = "夙忠：选择两张牌弃置，或点取消并失去1点体力",
  ["@@lingling__shenwu-inhand-turn"] = "神武",
}

local weizheng = General(extension, "lingling__weizheng", "tang", 3)
local mianjian = fk.CreateActiveSkill{
  name = "lingling__mianjian",
  anim_type = "support",
  target_filter = function (self, to_select, selected)
    return to_select ~= Self.id and #selected == 0 and not table.contains(Self:getTableMark("lingling__mianjian_record"), to_select)
  end,
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local mark = player:getTableMark("lingling__mianjian_record-turn")
    table.insertIfNeed(mark, target.id)
    room:setPlayerMark(player, "lingling__mianjian_record-turn", mark)
    local suc, dat = room:askForUseActiveSkill(target, "lingling__mianjian_viewas", "#lingling__mianjian-ask", true)
    if suc and dat then
      local card = Fk:cloneCard(dat.interaction)
      card.skillName = self.name
      card:addSubcards(dat.cards or {})
      local use = {
        from = target.id,
        tos = table.map(dat.targets, function(id)
          return {id}
        end),
        card = card,
      }
      room:useCard(use)
    end
    if not target.dead then
      local choices = {"mianjian_drawcards", "mianjian_debuff"}
      local choice = "mianjian_drawcards"
      if target.role == "lord" then
        choice = room:askForChoice(target, choices, self.name, "#lingling__mianjian-choice")
      else
        choice = table.random(choices, 1)[1]
      end
      if choice == "mianjian_debuff" then
        room:addPlayerMark(target, "@@lingling_mianjian_debuff", 1)
      else
        target:drawCards(2, self.name)
        if not target.dead then
          target:turnOver()
        end
      end
    end
  end,
}
local mianjian_refresh = fk.CreateTriggerSkill{
  name = "#lingling__mianjian_refresh",
  refresh_events = {fk.TurnEnd, fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    if player:hasSkill(mianjian, true, true) then
      if event == fk.TurnEnd then
        return player == target
      else
        return target:getMark("@@lingling_mianjian_debuff") > 0
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnEnd then
      room:setPlayerMark(player, "lingling__mianjian_record", player:getTableMark("lingling__mianjian_record-turn"))
    else
      room:setPlayerMark(target, "@@lingling_mianjian_debuff", 0)
      room:setPlayerMark(target, "@@lingling_mianjian_debuff-turn", 1)
    end
  end
}
local mianjian_targetmod = fk.CreateTargetModSkill{
  name = "#lingling__mianjiani_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and scope == Player.HistoryPhase and player:getMark("@@lingling_mianjian_debuff-turn") > 0 and player.phase ~= Player.NotActive then
      return - player:getMark("@@lingling_mianjian_debuff-turn")
    end
  end,
}
local mianjian_viewas = fk.CreateViewAsSkill{
  name = "lingling__mianjian_viewas",
  mute = true,
  interaction = function()
    local all_names = U.getAllCardNames("b")
    local names = U.getViewAsCardNames(Self, "lingling__mianjian_viewas", all_names)
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return #selected < 2
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 2 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
}
local mingjing = fk.CreateTriggerSkill{
  name = "lingling__mingjing",
  anim_type = "offensive",
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self.name) and target ~= player and data.card:isCommonTrick() and data.tos and
      table.contains(TargetGroup:getRealTargets(data.tos), player.id) and not data.card.multiple_targets and not target.dead
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if table.every(room.alive_players, function (p)
      return target.hp >= p.hp
    end) then
      self.cost_data = 1
      return player:canUseTo(Fk:cloneCard(data.card.name), target, {bypass_distances = true})
    else
      local targets = table.map(table.filter(room.alive_players, function (p)
        return table.every(room.alive_players, function (q)
          return p.hp >= q.hp
        end)
      end), Util.IdMapper)
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#lingling__mingjing-choose", self.name, true)
      if #to == 1 then
        self.cost_data = {tos = to}
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if self.cost_data == 1 then
      local card = Fk:cloneCard(data.card.trueName)
      card.skillName = self.name
      local use = {
        from = player.id,
        tos = {{target.id}},
        card = card,
      }
      room:useCard(use)
    else
      local to = room:getPlayerById(self.cost_data.tos[1])
      room:damage{
        from = player,
        to = to,
        damage = 1,
        skillName = self.name,
      }
    end
  end
}
Fk:addSkill(mianjian_viewas)
mianjian:addRelatedSkill(mianjian_refresh)
mianjian:addRelatedSkill(mianjian_targetmod)
weizheng:addSkill(mianjian)
weizheng:addSkill(mingjing)
Fk:loadTranslationTable{
  ["lingling__weizheng"] = "魏征",
  ["#lingling__weizheng"] = "鉴龙镜",
  ["designer:lingling__weizheng"] = "伶",
  ["illustrator:lingling__weizheng"] = "珊瑚虫",
  ["lingling__mianjian"] = "面谏",
  [":lingling__mianjian"] = "出牌阶段限一次，你可以指定一名上回合未以此法指定的角色，其将两张牌当任意基本牌使用，然后随机执行以下一项："..
  "摸两张牌并翻面；下回合使用【杀】次数上限-1。若其为主公，则随机改为其选择。",
  ["lingling__mianjian_viewas"] = "面谏",
  ["#lingling__mianjian-ask"] = "面谏：选择两张牌当任意基本牌使用",
  ["mianjian_drawcards"] = "摸两张牌并翻面",
  ["mianjian_debuff"] = "下回合使用【杀】次数上限-1",
  ["#lingling__mianjian-choice"] = "面谏：选择一项",
  ["@@lingling_mianjian_debuff"] = "面谏",
  ["@@lingling_mianjian_debuff-turn"] = "面谏",
  ["lingling__mingjing"] = "明镜",
  [":lingling__mingjing"] = "其他角色对你使用单体锦囊牌结算且生效后，若其体力为最多或之一，你视为对其使用同名牌，若不为最多或之一，"..
  "你可以对一名体力为最多或之一的角色造成1点伤害。"..
  "<br><br> <font color='#a40000'>故亦庶僚苟顺，难触龙鳞者欤？</font>",
  ["#lingling__mingjing-choose"] = "明镜：你可以对一名体力值最大的角色造成1点伤害",
}

local zhangsunwuji = General(extension, "lingling__zhangsunwuji", "tang", 3)
local weifeng = fk.CreateActiveSkill{
  name = "lingling__weifeng",
  anim_type = "special",
  target_filter = Util.FalseFunc,
  card_filter = Util.FalseFunc,
  interaction = function()
    local skills = {}
    for _, skill in ipairs(Self.player_skills) do
      if skill:isPlayerSkill(Self) and not skill.name:startsWith("#") then
        table.insert(skills, skill.name)
      end
    end
    return UI.ComboBox { choices = skills }
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local skill = self.interaction.data
    if skill then
      room:handleAddLoseSkills(player, "-" .. skill)
      if not player.dead then
        local cards = table.filter(player:getCardIds("h"), function (id)
          local c = Fk:getCardById(id)
          return c.type == Card.TypeBasic or c:isCommonTrick()
        end)
        if #cards > 0 then
          local card = Fk:getCardById(table.random(cards, 1)[1])
          local name = card.name
          local cids = room:getCardsFromPileByRule(name, 1, "drawPile")
          if #cids == 1 then
            room:obtainCard(player, cids, false, fk.ReasonJustMove)
          end
        end
      end
    end
  end,
}
local moubianCardNames = {
  --基本
  "slash", "jink", "peach", "analeptic",
  --普通锦囊
  "nullification", "duel", "ex_nihilo", "collateral", "snatch", "dismantlement", "fire_attack", "iron_chain",
  "archery_attack", "savage_assault", "amazing_grace", "god_salvation"
}
local createMoubianSkill = function(name)
  local skillname = "lingling__moubian_" .. name
  local moubian_viewas = fk.CreateViewAsSkill{
    name = skillname,
    anim_type = "special",
    pattern = name,
    prompt = skillname .. "-prompt",
    interaction = function()
      local all_names = {name}
      local names = U.getViewAsCardNames(Self, name, all_names)
      if #names > 0 then
        return U.CardNameBox { choices = names, all_choices = all_names }
      end
    end,
    card_filter = function ()
      return false
    end,
    view_as = function(self, cards)
      local card = Fk:cloneCard(self.interaction.data)
      card.skillName = self.name
      return card
    end,
    enabled_at_play = function(self, player)
      return player:usedSkillTimes(self.name, Player.HistoryRound) == 0
    end,
    enabled_at_response = function(self, player, response)
      return player:usedSkillTimes(self.name, Player.HistoryRound) == 0 and not response
    end,
  }
  Fk:addSkill(moubian_viewas)
  Fk:loadTranslationTable{
    [skillname] = Fk:translate(name),
    [":" .. skillname] = "每轮限一次，你可以视为使用一张【" .. Fk:translate(name) .. "】。",
    [skillname .. "-prompt"] = "你可以视为使用一张【" .. Fk:translate(name) .. "】。",
  }
end
--在这里循环添加技能
for _, n in ipairs(moubianCardNames) do
  createMoubianSkill(n)
end
local moubian = fk.CreateActiveSkill{
  name = "lingling__moubian",
  anim_type = "special",
  min_card_num = 2,
  target_num = 0,
  prompt = "#lingling__moubian",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter =  function (self, to_select, selected)
    if not Self:prohibitDiscard(to_select) then
      local toCard = Fk:getCardById(to_select)
      local skillName = "lingling__moubian_" .. toCard.trueName
      if not Fk.skills[skillName] then return end
      if Self:hasSkill(Fk.skills[skillName], true) then return end
      if #selected == 0 then
        return toCard.type == Card.TypeBasic or toCard:isCommonTrick()
      else
        local fromCard = Fk:getCardById(selected[1])
        return fromCard.trueName == toCard.trueName
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local cards = effect.cards
    room:throwCard(cards, self.name, player, player)
    if not player.dead then
      local name = Fk:getCardById(cards[1]).trueName
      local skillName = "lingling__moubian_" .. name
      if Fk.skills[skillName] and not player:hasSkill(Fk.skills[skillName], true) then
        room:handleAddLoseSkills(player, skillName)
      end
    end
  end,
}
local ciwei = fk.CreateTriggerSkill{
  name = "lingling__ciwei",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.TurnStart, fk.DamageInflicted},
  can_trigger = function (self, event, target, player, data)
    if event == fk.TurnStart then
      return player:hasSkill(self) and player ~= target and target.role == "lord"
    else
      return player == target and player:getMark("@@lingling__ciwei_protect") > 0
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      target:drawCards(1, self.name)
      if not player.dead then
        player:drawCards(1, self.name)
      end
      if not player.dead then
        local cids = room:askForDiscard(player, 2, 2, true, self.name, true, ".", "#lingling__ciwei-discard")
        if #cids == 2 and not player.dead then
          room:setPlayerMark(player, "@@lingling__ciwei_protect", 1)
        end
      end
    else
      room:setPlayerMark(player, "@@lingling__ciwei_protect", 0)
      return true
    end
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self, true, true) and target.role == "lord"
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "@@lingling__ciwei_protect", 0)
  end,
}
zhangsunwuji:addSkill(weifeng)
zhangsunwuji:addSkill(moubian)
zhangsunwuji:addSkill(ciwei)
Fk:loadTranslationTable{
  ["lingling__zhangsunwuji"] = "长孙无忌",
  ["#lingling__zhangsunwuji"] = "凌烟第一功",
  ["designer:lingling__zhangsunwuji"] = "玄蝶&伶",
  ["illustrator:lingling__zhangsunwuji"] = "珊瑚虫",
  ["lingling__weifeng"] = "威凤",
  [":lingling__weifeng"] = "出牌阶段限一次，你可以失去一个技能，然后随机获得一张与你手牌中随机一张基本牌或普通锦囊牌同名的牌。",
  ["lingling__moubian"] = "谋变",
  [":lingling__moubian"] = "出牌阶段限一次，你可以弃置至少两张同名基本牌或普通锦囊牌，获得一个“每轮限一次，你可以视为使用此牌”的技能。",
  ["lingling__ciwei"] = "辞位",
  [":lingling__ciwei"] = "主公回合开始时，若主公不为你，其与你各摸一张牌，然后你可以弃置两张牌，防止你受到的下一次伤害（直到主公下回合开始）。"..
  "<br><br> <font color='#a40000'>无忌戚里右族，英冠人杰。</font>",
  ["#lingling__moubian"] = "谋变：弃置至少两张同名牌，获得一个“每轮限一次，可以视为使用此牌”的技能！",
  ["#lingling__ciwei-discard"] = "辞位：你可以弃置两张牌，直到主公下回合开始，当你下一次受到伤害时，防止之",
  ["@@lingling__ciwei_protect"] = "辞位",
}

local licunxiao = General(extension, "lingling__licunxiao", "tang", 4)
local wuqian = fk.CreateTriggerSkill{
  name = "lingling__wuqian",
  anim_type = "offensive",
  events = {fk.TurnStart, fk.AfterCardUseDeclared, fk.CardUseFinished, fk.TargetSpecified, fk.Damage, fk.CardUsing},
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.TurnStart then
        return true
      elseif data.card and data.card.trueName == "slash" then
        if event == fk.AfterCardUseDeclared then
          return table.find(player:getCardIds("e"), function (id)
            return Fk:getCardById(id).trueName == "hualiu"
          end)
        elseif event == fk.CardUseFinished then
          return table.find(player:getCardIds("e"), function (id)
            return Fk:getCardById(id).trueName == "jueying"
          end)
        elseif event == fk.TargetSpecified then
          return table.find(player:getCardIds("e"), function (id)
            return Fk:getCardById(id).trueName == "zhuahuangfeidian"
          end) and not player.room:getPlayerById(data.to):isNude()
        elseif event == fk.Damage then
          return table.find(player:getCardIds("e"), function (id)
            return Fk:getCardById(id).trueName == "dilu" and not player:prohibitDiscard(id)
          end) and data.to ~= player and not data.to.dead
        elseif event == fk.CardUsing then
          return table.find(player:getCardIds("e"), function (id)
            return Fk:getCardById(id).trueName == "dayuan"
          end)
        end
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      return room:askForSkillInvoke(player, self.name, nil, "#lingling__wuqian-invoke")
    elseif event == fk.AfterCardUseDeclared or event == fk.CardUseFinished or event == fk.CardUsing then
      return true
    elseif event == fk.TargetSpecified then
      return room:askForSkillInvoke(player, self.name, nil, "#lingling__wuqian-zhuahuangfeidian::"..data.to)
    elseif event == fk.Damage then
      return room:askForSkillInvoke(player, self.name, nil, "#lingling__wuqian-dilu::"..data.to.id)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      local cards = {}
      for _, id in ipairs(room.draw_pile) do
        local card = Fk:getCardById(id)
        if card.sub_type == Card.SubtypeOffensiveRide or card.sub_type == Card.SubtypeDefensiveRide then
          table.insertIfNeed(cards, id)
        end
      end
      for _, id in ipairs(room.discard_pile) do
        local card = Fk:getCardById(id)
        if card.sub_type == Card.SubtypeOffensiveRide or card.sub_type == Card.SubtypeDefensiveRide then
          table.insertIfNeed(cards, id)
        end
      end
      for _, p in ipairs(room:getOtherPlayers(player)) do
        for _, id in ipairs(p:getCardIds("e")) do
          local card = Fk:getCardById(id)
          if card.sub_type == Card.SubtypeOffensiveRide or card.sub_type == Card.SubtypeDefensiveRide then
            table.insertIfNeed(cards, id)
          end
        end
      end
      if #cards == 0 then return end
      local card = table.random(cards)
      room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, true, player.id)
      if player.dead or not table.contains(player:getCardIds("h"), card) then return end
      card = Fk:getCardById(card)
      if player:prohibitUse(card) or player:isProhibited(player, card) then return end
      local yes = table.find(player:getCardIds("e"), function (id)
        local c = Fk:getCardById(id)
        return c.sub_type == card.sub_type and not player:hasEmptyEquipSlot(card.sub_type)
      end)
      room:useCard({
        from = player.id,
        tos = {{player.id}},
        card = card,
      })
      if yes and not player.dead then
        U.askForUseVirtualCard(room, player, "slash", nil, self.name, "#lingling__wuqian-slash", true, true, true, true)
      end
    elseif event == fk.AfterCardUseDeclared then
      data.additionalDamage = (data.additionalDamage or 0) + 1
    elseif event == fk.CardUseFinished then
      player:drawCards(1, self.name)
    elseif event == fk.TargetSpecified then
      local to = room:getPlayerById(data.to)
      local card = room:askForCardChosen(player, to, "he", self.name, "#lingling__wuqian-discard::"..data.to)
      room:throwCard(card, self.name, to, player)
    elseif event == fk.Damage then
      local card = table.find(player:getCardIds("e"), function (id)
        return Fk:getCardById(id).trueName == "dilu" and not player:prohibitDiscard(id)
      end)
      if not card then return end
      room:throwCard(card, self.name, player, player)
      room:doIndicate(player.id, {data.to.id})
      if data.to.dead then return end
      data.to:drawCards(2, self.name)
      if data.to.dead then return end
      data.to:turnOver()
    elseif event == fk.CardUsing then
      data.unoffsetableList = table.map(room.alive_players, Util.IdMapper)
    end
  end,
}
local wuqian_targetmod = fk.CreateTargetModSkill{
  name = "#lingling__wuqian_targetmod",
  main_skill = wuqian,
  bypass_times = function(self, player, skill, scope)
    return player:hasSkill(wuqian) and skill.trueName == "slash_skill" and
      table.find(player:getCardIds("e"), function (id)
        return Fk:getCardById(id).trueName == "zixing"
      end)
  end,
  extra_target_func = function(self, player, skill)
    if player:hasSkill(wuqian) and skill.trueName == "slash_skill" and
      table.find(player:getCardIds("e"), function (id)
        return Fk:getCardById(id).trueName == "chitu"
      end) then
      return 1
    end
  end,
}
wuqian:addRelatedSkill(wuqian_targetmod)
licunxiao:addSkill(wuqian)
Fk:loadTranslationTable{
  ["lingling__licunxiao"] = "李存孝",
  ["#lingling__licunxiao"] = "飞虎将军",
  ["designer:lingling__licunxiao"] = "伶",
  ["illustrator:lingling__licunxiao"] = "珊瑚虫",

  ["lingling__wuqian"] = "无前",
  [":lingling__wuqian"] = "回合开始时，你可以随机从牌堆、弃牌堆、其他角色场上获得一张坐骑牌并使用，若顶替了原坐骑牌，你视为使用一张"..
  "无距离限制的【杀】。若你装备区有：<br>"..
  "+1马：<br>"..
  "【骅骝】，你使用【杀】伤害+1；<br>"..
  "【绝影】，你使用【杀】后摸一张牌；<br>"..
  "【爪黄飞电】，你使用【杀】指定目标后可以弃置其一张牌；<br>"..
  "【的卢】，你使用【杀】对其他角色造成伤害后，你可以弃置此牌，令其摸两张牌并翻面；<br>"..
  "-1马：<br>"..
  "【大宛】，你使用【杀】无法抵消；<br>"..
  "【紫骍】，你使用【杀】无次数限制；<br>"..
  "【赤兔】，你使用【杀】可以额外指定一名目标。<br>"..
  "<br><br> <font color='#a40000'>王不过霸，将不过李。</font>",
  ["#lingling__wuqian-invoke"] = "无前：是否随机获得一张坐骑牌并使用之？",
  ["#lingling__wuqian-slash"] = "无前：你可以视为使用一张无距离限制的【杀】",
  ["#lingling__wuqian-zhuahuangfeidian"] = "无前：是否弃置 %dest 一张牌？",
  ["#lingling__wuqian-discard"] = "无前：弃置 %dest 一张牌",
  ["#lingling__wuqian-dilu"] = "无前：是否弃置【的卢】，令 %dest 摸两张牌并翻面？",
}

local qinqiong = General(extension, "lingling__qinqiong", "tang", 4)
local guonan = fk.CreateTriggerSkill{
  name = "lingling__guonan",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = #table.find(room.players, function (p)
      return p.role == "rebel"
    end)
    if n == 0 then
      n = #room.players / 2
    end
    local cards = room:getTag(self.name) or {}
    for i = 1, n, 1 do
      table.insert(cards, room:printCard("ling__drowning", Card.Spade, 4).id)
      table.insert(cards, room:printCard("unexpectation", Card.Heart, 3).id)
    end
    room:setTag(self.name, cards)
    for _, id in ipairs(cards) do
      if room:getCardArea(id) == Card.Void then
        table.removeOne(room.void, id)
        table.insert(room.draw_pile, math.random(#room.draw_pile), id)
        room:setCardArea(id, Card.DrawPile, nil)
      end
    end
    room:doBroadcastNotify("UpdateDrawPile", tostring(#room.draw_pile))
  end,
}
local fenwei = fk.CreateTriggerSkill{
  name = "lingling__fenwei",
  anim_type = "drawcard",
  events = {fk.TargetConfirmed, fk.RoundEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.TargetConfirmed then
        return table.contains({"drowning", "fire_attack", "unexpectation", "duel"}, data.card.trueName)
      elseif event == fk.RoundEnd then
        return #player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function (e)
          return table.contains({"drowning", "fire_attack", "unexpectation", "duel"}, e.data[1].card.trueName)
        end, Player.HistoryRound) < 2
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.TargetConfirmed then
      return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__fenwei-invoke::"..target.id)
    elseif event == fk.RoundEnd then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetConfirmed then
      player:drawCards(1, self.name)
      if player.dead or target.dead or player:isNude() then return end
      local card = room:askForCard(player, 1, 1, true, self.name, true, nil, "#lingling__fenwei-give::"..target.id)
      if #card > 0 then
        room:moveCardTo(card, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, false, player.id)
      end
    elseif event == fk.RoundEnd then
      local cards = {}
      for _, name in ipairs({"drowning", "fire_attack", "unexpectation", "duel"}) do
        table.insertTable(cards, room:getCardsFromPileByRule(name, 1, "allPiles"))
      end
      if #cards > 0 then
        local n = 2 - #room.logic:getEventsOfScope(GameEvent.UseCard, 2, function (e)
          return table.contains({"drowning", "fire_attack", "unexpectation", "duel"}, e.data[1].card.trueName)
        end, Player.HistoryRound)
        room:moveCardTo(table.random(cards, n), Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
      end
    end
  end,
}
qinqiong:addSkill(guonan)
qinqiong:addSkill(fenwei)
Fk:loadTranslationTable{
  ["lingling__qinqiong"] = "秦琼",
  ["#lingling__qinqiong"] = "龙骧大将军",
  ["designer:lingling__qinqiong"] = "伶",
  ["illustrator:lingling__qinqiong"] = "珊瑚虫",

  ["lingling__guonan"] = "国难",
  [":lingling__guonan"] = "游戏开始时，牌堆加入X张【水淹七军】和X张【出其不意】（X为反贼数）。",
  ["lingling__fenwei"] = "奋威",
  [":lingling__fenwei"] = "当一名角色成为【水淹七军】【火攻】【出其不意】【决斗】的目标后，你可以摸一张牌，然后可以交给其一张牌。"..
  "轮次结束时，若本轮所有角色使用这些牌的次数少于两次，你随机获得这些牌中的X种各一张牌（X为2-使用次数）。",
  ["#lingling__fenwei-invoke"] = "奋威：你可以摸一张牌，然后可以交给 %dest 一张牌",
  ["#lingling__fenwei-give"] = "奋威：你可以交给 %dest 一张牌",
}

return extension
